<template>
  <el-autocomplete ref="autocompleteRef" :style="{
    width: proxy.$size(width, '100%'),
  }" v-model="keyword" v-bind="{
    placeholder: '请输入',
    clearable: true,
    ...$attrs,
    disabled: typeof $attrs.disabled === 'function' ? $attrs.disabled(data) : $attrs.disabled
  }" :fetch-suggestions="querySearch" @select="handleSelect" @clear="handleClear">
    <template #suffix v-if="addBtn && dataInfo.isNew">
      <el-button type="primary" @click.stop="addBtn(dataName ? data[dataName] : data, dataInfo)" size="small"
        :disabled="!dataInfo.isNew">添加</el-button>
    </template>
    <template #default="{ item }">
      <div v-html="proxy.$highlightedText(item.value, dataName ? data[dataName] : data)"></div>
    </template>
  </el-autocomplete>
</template>
<script setup lang="ts">
const { proxy } = getCurrentInstance() as any;
//获取父级数据
const props = withDefaults(
  defineProps<{
    data: any;
    dataName?: any;
    width?: string | number;
    searchBtn?: Function;
    addBtn?: Function;
  }>(),
  {

  },
);
// 获取 el-autocomplete 组件实例
const autocompleteRef: any = ref(null);
const dataInfo: any = reactive({
  isNew: false,
  options: []
})
const keyword = computed({
  get() {
    if (props.data) {
      return props.dataName ? props.data[props.dataName] : props.data;
    } else {
      return ""
    }
  },
  set(val) {
    if (props.dataName) {
      props.data[props.dataName] = val
    } else {
      props.data = val;
    }
  },
});

const querySearch = (queryString: string, cb: any) => {
  dataInfo.isNew = false
  if (props.searchBtn && typeof props.searchBtn === 'function') {
    dataInfo.options = []
    props.searchBtn(queryString, props.data, dataInfo, () => {
      getQuerySearch(queryString, cb)
    })
  } else {
    getQuerySearch(queryString, cb)
  }
}
const getQuerySearch = (queryString: string, cb: any) => {
  const _options = dataInfo.options.sort((a: any, b: any) => a.value.length - b.value.length);
  const _findIndex = _options.findIndex((el: any) => queryString === el.value)
  if (queryString && _findIndex === -1) {
    dataInfo.isNew = true
  }
  cb(_options)
}


const handleSelect = (item: any) => {
  dataInfo.isNew = false
  changeBtn(item)
  // 移除焦点
  // 使用 $refs 获取到组件实例后，再获取内部的 input 元素并调用 blur 方法
  nextTick(() => {
    const inputEl = autocompleteRef.value;
    if (inputEl) {
      inputEl.blur();
    }
  });

}
const emit = defineEmits<{
  //fn为父组件引入子组件是定义的子组件事件属性，可随意定义
  (event: 'changeBtn', item: any, form: any): void;
}>();
const handleClear = () => {
  emit('changeBtn', {}, props.data)
};
const changeBtn = (item: any) => {
  emit('changeBtn', item, props.data)
};
onMounted(() => {

});
</script>
<style scoped></style>
